package application.common.util;

import java.sql.SQLException;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.DbKit;

public class ExtDbUtil {

	/**
	 * 开始事务
	 * 
	 * @throws SQLException
	 */
	public static void beginTran() throws SQLException {
		DbKit.getConfig().setThreadLocalConnection(DbKit.getConfig().getConnection());
		DbKit.getConfig().getThreadLocalConnection().setAutoCommit(false);
	}

	/**
	 * 开始事务
	 * 
	 * @param configName
	 * @throws SQLException
	 */
	public static void beginTran(String configName) throws SQLException {
		DbKit.getConfig(Db.use().getConfig().getName()).setThreadLocalConnection(DbKit.getConfig(configName).getConnection());
		DbKit.getConfig(configName).getThreadLocalConnection().setAutoCommit(false);
	}

	/**
	 * 事务回滚
	 * 
	 * @throws SQLException
	 */
	public static void rollback() throws SQLException {
		DbKit.getConfig().getThreadLocalConnection().rollback();
		DbKit.getConfig().getThreadLocalConnection().setAutoCommit(true);
		DbKit.getConfig().removeThreadLocalConnection();
	}

	/**
	 * 事务回滚
	 * 
	 * @param configName
	 * @throws SQLException
	 */
	public static void rollback(String configName) throws SQLException {
		DbKit.getConfig(configName).getThreadLocalConnection().rollback();
		DbKit.getConfig(configName).getThreadLocalConnection().setAutoCommit(true);
		DbKit.getConfig(configName).removeThreadLocalConnection();
	}

	/**
	 * 事务提交
	 * 
	 * @throws SQLException
	 */
	public static void commit() throws SQLException {
		DbKit.getConfig().getThreadLocalConnection().commit();
		DbKit.getConfig().getThreadLocalConnection().setAutoCommit(true);
		DbKit.getConfig().removeThreadLocalConnection();
	}

	/**
	 * 事务提交
	 * 
	 * @param configName
	 * @throws SQLException
	 */
	public static void commit(String configName) throws SQLException {
		DbKit.getConfig(configName).getThreadLocalConnection().commit();
		DbKit.getConfig(configName).getThreadLocalConnection().setAutoCommit(true);
		DbKit.getConfig(configName).removeThreadLocalConnection();
	}

}
